<template>
  <div class="register-container">
    <div class="register-form-wrapper">
      <div class="register-box">
        <h2 class="title">创建新账户</h2>
        <div class="subtitle">加入我们的图床管理系统</div>
        
        <form @submit.prevent="handleRegister">
          <div class="form-group" :class="{'error': errors.userName}">
            <label for="username">用户名 <span class="required">*</span></label>
            <div class="input-wrapper">
              <i class="input-icon">👤</i>
              <input 
                type="text" 
                id="username" 
                v-model.trim="registerForm.userName" 
                placeholder="请输入用户名"
                @blur="validateUserName"
                @input="validateUserName"
              />
            </div>
            <div class="error-tip" v-if="errors.userName">{{ errors.userName }}</div>
          </div>
          
          <div class="form-group" :class="{'error': errors.nickName}">
            <label for="nickname">昵称 <span class="required">*</span></label>
            <div class="input-wrapper">
              <i class="input-icon">📝</i>
              <input 
                type="text" 
                id="nickname" 
                v-model.trim="registerForm.nickName" 
                placeholder="请输入昵称"
                @blur="validateNickName"
                @input="validateNickName"
              />
            </div>
            <div class="error-tip" v-if="errors.nickName">{{ errors.nickName }}</div>
          </div>
          
          <div class="form-group" :class="{'error': errors.password}">
            <label for="password">密码 <span class="required">*</span></label>
            <div class="input-wrapper">
              <i class="input-icon">🔒</i>
              <input 
                :type="showPassword ? 'text' : 'password'" 
                id="password" 
                v-model="registerForm.password" 
                placeholder="请输入密码"
                @blur="validatePassword"
                @input="validatePassword"
              />
              <i class="toggle-password" @click="showPassword = !showPassword">
                {{ showPassword ? '👁️' : '👁️‍🗨️' }}
              </i>
            </div>
            <div class="error-tip" v-if="errors.password">{{ errors.password }}</div>
            
            <!-- 密码强度指示器 -->
            <div class="password-strength" v-if="registerForm.password">
              <div class="strength-label">密码强度: <span :class="passwordStrengthClass">{{ passwordStrengthText }}</span></div>
              <div class="strength-bar">
                <div class="strength-indicator" :style="{ width: passwordStrength + '%', backgroundColor: passwordStrengthColor }"></div>
              </div>
            </div>
          </div>
          
          <div class="form-group" :class="{'error': errors.confirmPassword}">
            <label for="confirm-password">确认密码 <span class="required">*</span></label>
            <div class="input-wrapper">
              <i class="input-icon">🔐</i>
              <input 
                :type="showConfirmPassword ? 'text' : 'password'" 
                id="confirm-password" 
                v-model="confirmPassword" 
                placeholder="请再次输入密码"
                @blur="validateConfirmPassword"
                @input="validateConfirmPassword"
              />
              <i class="toggle-password" @click="showConfirmPassword = !showConfirmPassword">
                {{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
              </i>
            </div>
            <div class="error-tip" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</div>
          </div>
          
          <div class="form-group" :class="{'error': errors.phone}">
            <label for="phone">电话</label>
            <div class="input-wrapper">
              <i class="input-icon">📱</i>
              <input 
                type="text" 
                id="phone" 
                v-model.trim="registerForm.phone" 
                placeholder="请输入电话号码（可选）"
                @blur="validatePhone"
                @input="validatePhone"
              />
            </div>
            <div class="error-tip" v-if="errors.phone">{{ errors.phone }}</div>
          </div>
          
          <div class="form-group" :class="{'error': errors.email}">
            <label for="email">邮箱</label>
            <div class="input-wrapper">
              <i class="input-icon">📧</i>
              <input 
                type="email" 
                id="email" 
                v-model.trim="registerForm.email" 
                placeholder="请输入电子邮箱（可选）"
                @blur="validateEmail"
                @input="validateEmail"
              />
            </div>
            <div class="error-tip" v-if="errors.email">{{ errors.email }}</div>
          </div>
          
          <button 
            type="submit"
            :disabled="loading || !isFormValid" 
            class="register-button"
            :class="{'disabled': !isFormValid}"
          >
            <span v-if="loading" class="loading-spinner">⟳</span>
            <span v-else>注册</span>
          </button>
        </form>
        
        <!-- 错误信息提示 -->
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <!-- 注册状态提示 -->
        <div v-if="registerStatus" class="status-message">
          {{ registerStatus }}
        </div>
        
        <div class="login-link">
          已有账号？<a href="javascript:void(0)" @click="goToLogin">返回登录</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import axios from 'axios';
import md5 from 'md5';
import { useRouter } from 'vue-router';

const router = useRouter();
const loading = ref(false);
const errorMessage = ref('');
const registerStatus = ref('');
const confirmPassword = ref('');
const showPassword = ref(false);
const showConfirmPassword = ref(false);

// 表单错误信息
const errors = reactive({
  userName: '',
  nickName: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: ''
});

const registerForm = reactive({
  userName: '',
  nickName: '',
  password: '',
  phone: '',
  email: ''
});

// 表单验证方法
const validateUserName = () => {
  if (!registerForm.userName.trim()) {
    errors.userName = '用户名不能为空';
    return false;
  }
  
  if (registerForm.userName.trim().length < 3) {
    errors.userName = '用户名长度至少为3个字符';
    return false;
  }
  
  errors.userName = '';
  return true;
};

const validateNickName = () => {
  if (!registerForm.nickName.trim()) {
    errors.nickName = '昵称不能为空';
    return false;
  }
  
  errors.nickName = '';
  return true;
};

const validatePassword = () => {
  if (!registerForm.password) {
    errors.password = '密码不能为空';
    return false;
  }
  
  if (registerForm.password.length < 6) {
    errors.password = '密码长度至少为6个字符';
    return false;
  }
  
  errors.password = '';
  validateConfirmPassword(); // 重新验证确认密码
  return true;
};

const validateConfirmPassword = () => {
  if (!confirmPassword.value) {
    errors.confirmPassword = '请确认密码';
    return false;
  }
  
  if (confirmPassword.value !== registerForm.password) {
    errors.confirmPassword = '两次输入的密码不一致';
    return false;
  }
  
  errors.confirmPassword = '';
  return true;
};

const validatePhone = () => {
  // 如果电话号码为空但不是必填，则通过验证
  if (!registerForm.phone.trim()) {
    errors.phone = '';
    return true;
  }
  
  // 简单的电话号码格式验证
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(registerForm.phone.trim())) {
    errors.phone = '请输入正确的手机号码';
    return false;
  }
  
  errors.phone = '';
  return true;
};

const validateEmail = () => {
  // 如果邮箱为空但不是必填，则通过验证
  if (!registerForm.email.trim()) {
    errors.email = '';
    return true;
  }
  
  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(registerForm.email.trim())) {
    errors.email = '请输入正确的电子邮箱地址';
    return false;
  }
  
  errors.email = '';
  return true;
};

// 检查表单是否有效
const isFormValid = computed(() => {
  return validateUserName() &&
         validateNickName() && 
         validatePassword() && 
         validateConfirmPassword() && 
         validatePhone() && 
         validateEmail();
});

// 密码强度计算
const passwordStrength = computed(() => {
  const password = registerForm.password;
  if (!password) return 0;
  
  let strength = 0;
  
  // 长度检查
  if (password.length >= 6) strength += 20;
  if (password.length >= 8) strength += 10;
  if (password.length >= 12) strength += 10;
  
  // 复杂度检查
  if (/[A-Z]/.test(password)) strength += 15; // 大写字母
  if (/[a-z]/.test(password)) strength += 15; // 小写字母
  if (/[0-9]/.test(password)) strength += 15; // 数字
  if (/[^A-Za-z0-9]/.test(password)) strength += 15; // 特殊字符
  
  return Math.min(100, strength);
});

const passwordStrengthClass = computed(() => {
  const strength = passwordStrength.value;
  if (strength < 40) return 'weak';
  if (strength < 70) return 'medium';
  return 'strong';
});

const passwordStrengthText = computed(() => {
  const strength = passwordStrength.value;
  if (strength < 40) return '弱';
  if (strength < 70) return '中';
  return '强';
});

const passwordStrengthColor = computed(() => {
  const strength = passwordStrength.value;
  if (strength < 40) return '#e74c3c'; // 红色
  if (strength < 70) return '#f39c12'; // 橙色
  return '#2ecc71'; // 绿色
});

const handleRegister = async () => {
  // 验证所有字段
  validateUserName();
  validateNickName();
  validatePassword();
  validateConfirmPassword();
  validatePhone();
  validateEmail();
  
  if (!isFormValid.value) {
    return;
  }
  
  // 清除之前的错误信息
  errorMessage.value = '';
  registerStatus.value = '';
  
  try {
    loading.value = true;
    
    // MD5加密密码
    const encryptedPwd = md5(registerForm.password);
    
    // 构建请求数据
    const requestData = {
      userName: registerForm.userName,
      nickName: registerForm.nickName,
      firstPwd: encryptedPwd
    };
    
    // 添加可选字段
    if (registerForm.phone) {
      requestData.phone = registerForm.phone;
    }
    
    if (registerForm.email) {
      requestData.email = registerForm.email;
    }
    
    console.log('正在发送注册请求...');
    
    // 发送注册请求
    const response = await axios.post('/api/reg', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('注册响应:', response.data);
    
    if (response.data.code === 0) {
      registerStatus.value = '注册成功，即将跳转到登录页...';
      
      // 延时跳转到登录页
      setTimeout(() => {
        router.push('/login');
      }, 1500);
    } else if (response.data.code === 2) {
      errorMessage.value = '用户名已存在，请更换用户名';
    } else {
      errorMessage.value = '注册失败，请稍后重试';
    }
  } catch (error) {
    console.error('注册请求错误:', error);
    errorMessage.value = '注册失败，请稍后重试';
    
    if (error.response) {
      console.error('错误状态:', error.response.status);
      console.error('错误数据:', error.response.data);
    } else if (error.request) {
      console.error('未收到响应');
      errorMessage.value = '服务器未响应，请检查网络连接';
    } else {
      console.error('错误信息:', error.message);
    }
  } finally {
    loading.value = false;
  }
};

const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 40px 0;
}

.register-form-wrapper {
  width: 100%;
  max-width: 500px;
  padding: 20px;
  margin: 0 auto;
}

.register-box {
  background: white;
  padding: 35px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

.register-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 10px;
  color: #2c3e50;
  font-weight: 600;
  font-size: 24px;
}

.subtitle {
  text-align: center;
  margin-bottom: 30px;
  color: #7f8c8d;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group.error .input-wrapper {
  border-color: #e74c3c;
}

label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #34495e;
  font-size: 14px;
}

.required {
  color: #e74c3c;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 8px;
  transition: all 0.3s;
  background: #f9f9f9;
}

.input-wrapper:focus-within {
  border-color: #4a90e2;
  box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.1);
  background: #fff;
}

.input-icon {
  padding: 0 12px;
  color: #95a5a6;
  font-style: normal;
}

input {
  width: 100%;
  padding: 12px 10px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  background: transparent;
  outline: none;
}

.toggle-password {
  padding: 0 12px;
  cursor: pointer;
  color: #95a5a6;
  font-style: normal;
  user-select: none;
}

.error-tip {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
}

.password-strength {
  margin-top: 10px;
  font-size: 13px;
}

.strength-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.strength-label .weak { color: #e74c3c; }
.strength-label .medium { color: #f39c12; }
.strength-label .strong { color: #2ecc71; }

.strength-bar {
  height: 4px;
  background-color: #eee;
  border-radius: 2px;
  overflow: hidden;
}

.strength-indicator {
  height: 100%;
  transition: width 0.3s, background-color 0.3s;
}

.register-button {
  width: 100%;
  padding: 12px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s;
  margin-top: 10px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.register-button:hover:not(.disabled) {
  background-color: #3a7bc8;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(74, 144, 226, 0.2);
}

.register-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.register-button.disabled {
  background-color: #a0c3e8;
  cursor: not-allowed;
}

.loading-spinner {
  animation: spin 1s linear infinite;
  font-size: 18px;
  display: inline-block;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.error-message {
  margin-top: 20px;
  color: #e74c3c;
  font-size: 14px;
  text-align: center;
  padding: 10px;
  background-color: rgba(231, 76, 60, 0.1);
  border-radius: 6px;
}

.status-message {
  margin-top: 20px;
  color: #2ecc71;
  font-size: 14px;
  text-align: center;
  padding: 10px;
  background-color: rgba(46, 204, 113, 0.1);
  border-radius: 6px;
}

.login-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
}

.login-link a {
  color: #4a90e2;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s;
}

.login-link a:hover {
  color: #3a7bc8;
  text-decoration: underline;
}
</style> 